package com.sgb.kjwl.viewmodel.transport;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.databinding.ObservableField;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.model.entity.transport.GoodsHallFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.TransportRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.transport.GoodsFragment;
import com.sgb.kjwl.view.ui.fragment.transport.GoodsListFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow.DEFAULT_GOODS_TYPE;

public class GoodsInfofrgModel3 extends BaseViewModel {

    private GoodsListFragment goodsListFragment;
    private GoodsFragment goodsFragment;
    private TransportRepertory repertory;
    public ObservableField<GoodsHallFilterEntity> filterEntity = new ObservableField<>(new GoodsHallFilterEntity());
    public ObservableField<GoodsSourceLocationEntity> sendLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsSourceLocationEntity> purposeLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsInfoTypeEntity3> sourceType = new ObservableField<>(new GoodsInfoTypeEntity3());
    private Map map;
    private int pageSize = 10;
    private int pageNum = 1;
    private int total;
    private String areaCode;
    private boolean isStartAppFirstLoadData = true;
    public String websiteNo;//主页身份no
    public String websiteType;//主页身份(个人、企业、团队)

    public GoodsInfofrgModel3(GoodsListFragment activity, TransportRepertory repertory) {
        this.goodsListFragment = activity;
        this.repertory = repertory;
    }

    public GoodsInfofrgModel3(GoodsFragment fragment, TransportRepertory repertory) {
        this.goodsFragment = fragment;
        this.repertory = repertory;
    }

    public void getList(Context context,int page){
        if (!TextUtils.isEmpty(websiteNo) && !TextUtils.isEmpty(websiteType)) {
            //前台自营走老接口

        }else {

        }
    }

    public void getGoodsTypeData() {
        String sourceString = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.GOODS_INFO_TYPE, "");
        List<GoodsInfoTypeEntity3> sourcesType = new Gson().fromJson(sourceString, new TypeToken<List<GoodsInfoTypeEntity3>>() {
        }.getType());
        goodsListFragment.getGoodsTypeData(sourcesType);

        String carsTypeString = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.CARS_INFO_TYPE, "");
        String carsLengthString = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.CARS_INFO_LENGTH, "");
        List<GoodsInfoTypeEntity3> carsType = new Gson().fromJson(carsTypeString, new TypeToken<List<GoodsInfoTypeEntity3>>() {
        }.getType());
        List<GoodsInfoTypeEntity3> carsLengthType = new Gson().fromJson(carsLengthString, new TypeToken<List<GoodsInfoTypeEntity3>>() {
        }.getType());
        goodsListFragment.getCarsTypeData(carsType);
        goodsListFragment.getCarsLengthData(carsLengthType);

    }

    private void getGoodsSuccess(BaseEntity<ProListEntity<List<GoodsInfoEntity>>> data) {
        if (data == null)
            return;
        if (data.getState().equals(APIManager.RESPONSE_OK)) {
            if (data.getData() == null || data.getData().getList() == null) {
                MToast.showToast(goodsListFragment.getActivity(), "暂无数据");
                return;
            }
            if (goodsListFragment != null)
                goodsListFragment.refreshGoodsInfoList(data.getData().getList(), data.getData().isLastPage());
        } else {
            MToast.showToast(goodsListFragment.getActivity(), data.getState());
        }
    }

    private void getGoodsFail(Throwable t) {
        t.printStackTrace();
        goodsListFragment.finishRefreshOrLoadMore();
        MToast.showToast(goodsListFragment.getActivity(), t.getMessage());
    }

    public void getAddressModel() {
        if (goodsListFragment.getActivity() == null) {
            return;
        }
        DialogHelper.showProgressDialog(goodsListFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {

                if (data != null && data.size() > 0) {
                    DialogHelper.dismissProgressDialog();
                    goodsListFragment.initAddressData(data);
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {

            }
        });
    }

    //货物类型
    public void getGoodsType() {
        NewAPIManager.getInstance().getLogisticsAPI().getAllGoodsType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    Log.v("responsBody", new Gson().toJson(response.body().getData()));
                    if (goodsListFragment != null)
                        goodsListFragment.getGoodsTypeData(response.body().getData());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.GOODS_INFO_TYPE, new Gson().toJson(response.body().getData()));
                } else {
//                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //货车类型
    public void getCarsType() {
        APIManager.getInstance().getDriverAPI().getCarType("1").enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    if (goodsListFragment != null)
                        goodsListFragment.getCarsTypeData(response.body().getData());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.CARS_INFO_TYPE, new Gson().toJson(response.body().getData()));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //货车长度
    public void getCarsLength() {
        APIManager.getInstance().getDriverAPI().getCarLenType("1").enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    if (goodsListFragment != null)
                        goodsListFragment.getCarsLengthData(response.body().getData());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.CARS_INFO_LENGTH, new Gson().toJson(response.body().getData()));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //运输方式
    public void getTransType() {
        APIManager.getInstance().getDriverAPI().getTransType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.TRANSPORT_TYPE, new Gson().toJson(response.body().getData()));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //装载方式
    public void getHandleType() {
        APIManager.getInstance().getDriverAPI().getHandleType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.CARS_HANDLING_TYPE, new Gson().toJson(response.body().getData()));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //付款方式
    public void getPayType() {
        APIManager.getInstance().getDriverAPI().getPayType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PAY_TYPE, new Gson().toJson(response.body().getData()));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }

    //发票方式
    public void getInvoiceType() {
        APIManager.getInstance().getDriverAPI().getInvoiceType().enqueue(new Callback<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Response<BaseEntity<List<GoodsInfoTypeEntity3>>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.INVOICE_TYPE, new Gson().toJson(response.body().getData()));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<GoodsInfoTypeEntity3>>> call, Throwable t) {
            }
        });
    }


    public void goodsSourceStatusCheck(String no, int position) {
        NewAPIManager.getInstance().getLogisticsAPI().goodsSourceStatusCheck(no).enqueue(new Callback<BaseEntity<CheckStateEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<CheckStateEntity>> call, Response<BaseEntity<CheckStateEntity>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    goodsListFragment.checkGoodsState(position, response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<CheckStateEntity>> call, Throwable t) {
            }
        });
    }


    public void getUrl(String id, int pattern) {
        String detail = "";
        if (pattern == 0) {
            detail = "sourceDetails";
        } else {
            detail = "biddingFindGoodsDetails";
        }
        DialogHelper.showProgressDialog(goodsListFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getTeamPriceAPI().getUrlSetting(detail).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id + "&areaCode=" + repertory.getAreaCode();
                    WebViewX5HostActivity.start(goodsListFragment.getActivity(), url);
                } else {
                    MToast.showToast(goodsListFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getGoodsList(Context context, int pageNum, String goodsType, int pattern, String websiteType, String websiteNo) {
        if (map == null) {
            map = new HashMap();
        } else {
            map.clear();
        }
        map.put("page", pageNum);
        map.put("limit", pageSize);
        if (null != filterEntity.get()) {
            if ((filterEntity.get().getMinWeight() == null)) {
                map.put("minWeight", 0);
            } else {
                map.put("minWeight", Double.valueOf(filterEntity.get().getMinWeight()));
            }

            if (filterEntity.get().getMaxWeight() == null) {
                map.put("maxWeight", 0);
            } else {
                map.put("maxWeight", Double.valueOf(filterEntity.get().getMaxWeight()));
            }

            if ((filterEntity.get().getMinWeight() == null)) {
                map.put("volume", 0);
            } else {
                map.put("volume", Double.valueOf(filterEntity.get().getVolume()));
            }

            if (filterEntity.get().getMaxWeight() == null) {
                map.put("maxVolume", 0);
            } else {
                map.put("maxVolume", Double.valueOf(filterEntity.get().getMaxVolume()));
            }

            if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
                map.put("needVideo", "0");
            } else {
                map.put("needVideo", filterEntity.get().getNeedVideo());
            }

            if (TextUtils.isEmpty(filterEntity.get().getShipmentEndTime())) {
                map.put("shipmentEndTime", 0);
            } else {
                map.put("shipmentEndTime", Long.valueOf(filterEntity.get().getShipmentEndTime()));
            }

            if (!TextUtils.isEmpty(filterEntity.get().getShipmentTime())) {
                map.put("shipmentTime", Long.valueOf(filterEntity.get().getShipmentTime()));
            }

            String typeNos = "";
            if (null != filterEntity.get().getCarType() && filterEntity.get().getCarType().size() > 0) {
                for (GoodsInfoTypeEntity3 entity : filterEntity.get().getCarType()) {
                    if (!TextUtils.isEmpty(entity.getNo())) {
                        typeNos += entity.getNo() + ",";
                    }
                }
            }
            if (!TextUtils.isEmpty(typeNos)) {
                typeNos = typeNos.substring(0, typeNos.length() - 1);
            }
            map.put("carTypeNos", typeNos);

            String lenNos = "";
            if (null != filterEntity.get().getLengthType() && filterEntity.get().getLengthType().size() > 0) {
                for (GoodsInfoTypeEntity3 entity : filterEntity.get().getLengthType()) {
                    if (!TextUtils.isEmpty(entity.getNo())) {
                        lenNos += entity.getNo() + ",";
                    }
                }
            }
            if (!TextUtils.isEmpty(lenNos)) {
                lenNos = lenNos.substring(0, lenNos.length() - 1);
            }
            map.put("carLenNos", lenNos);

            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                    map.put("provinceNo", "");
                } else {
                    map.put("provinceNo", sendLocation.get().getProvinceNo());
                }
            }

            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                    map.put("cityNo", "");
                } else {
                    map.put("cityNo", sendLocation.get().getCityNo());
                }
            }
            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                    map.put("districtNo", "");
                } else {
                    map.put("districtNo", sendLocation.get().getAreaNo());
                }
            }
            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                    map.put("destProvinceNo", "");
                } else {
                    map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
                }
            }

            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {

                    map.put("destCityNo", "");
                } else {
                    map.put("destCityNo", purposeLocation.get().getCityNo());
                }
            }

            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                    map.put("destDistrictNo", "");
                } else {
                    map.put("destDistrictNo", purposeLocation.get().getAreaNo());
                }
            }
            if (null != goodsType) {
                if (TextUtils.isEmpty(goodsType) || goodsType.equals(DEFAULT_GOODS_TYPE)) {
                    map.put("goodsTypeNo", "");
                } else {
                    map.put("goodsTypeNo", goodsType);
                }
            }
            if (LocationUtil.isOpenLocation(context)) {
                if (LocationUtil.getCurrentLongitude() != 0.00) {
                    map.put("ipLongitude", LocationUtil.getCurrentLongitude());
                    map.put("ipLatitude", LocationUtil.getCurrentLatitude());
                }
            }

            if (pattern == 0) {//普通货源
                map.put("pattern", 0);
            } else if (pattern == 1) {//竞价货源
                map.put("pattern", 1);
            } else if (pattern == 3) {//查询自营货源
                if (!TextUtils.isEmpty(websiteNo) && !TextUtils.isEmpty(websiteType)) {
                    switch (websiteType) {
                        case "0":
                            map.put("userNo", websiteNo);
                            break;
                        case "1":
                            map.put("companyNo", websiteNo);
                            break;
                        case "2":
                            map.put("teamNo", websiteNo);
                            break;
                    }
                }
            }
            if (isStartAppFirstLoadData && pattern == 0) {
                String json = MkvUtils.get().getString(MkvUtils.CacheModular, CacheMarker.LogisticsGoodsList, "");
                if (!TextUtils.isEmpty(json)) {
                    BaseEntity<ProListEntity<List<GoodsInfoEntity>>> data = new Gson().fromJson(json, new TypeToken<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>>() {
                    }.getType());
                    getGoodsSuccess(data);
                }
                isStartAppFirstLoadData = false;
            }

            DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
            if (pattern == 0) {
                NewAPIManager.getInstance().getLogisticsAPI().getFilterSourceList(map).enqueue(new Callback<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> call, Response<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (pageNum == 1) {
                            //获取从网络请求下来的数据的哈希值
                            String dataJson = DatalUtils.getInstance().getJsonString(response.body());
                            String mHashNet = DatalUtils.strToHashKey(dataJson);
                            String hashData = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.LogisticsGoodsList);
                            if (!mHashNet.equals(hashData)) {
                                getGoodsSuccess(response.body());
                                MkvUtils.get().putString(MkvUtils.CacheModular, CacheMarker.LogisticsGoodsList, dataJson);
                            }
                        } else {
                            getGoodsSuccess(response.body());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                        getGoodsFail(t);
                    }
                });
            } else {
                NewAPIManager.getInstance().getLogisticsAPI().getFilterSourceList(map).enqueue(new Callback<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> call, Response<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        getGoodsSuccess(response.body());

                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ProListEntity<List<GoodsInfoEntity>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                        getGoodsFail(t);
                    }
                });
            }
        }
    }
}
